package com.pencil.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tiles.TilesContainer;
import org.apache.tiles.servlet.context.ServletUtil;

public class ActionForward {
	private String url;
	private boolean isRedirect = false;
	private boolean isTiles = true;

	public ActionForward() {
		isRedirect = false;
		url = "";
	}

	public ActionForward(String url, boolean isRedirect) {
		this.url = url;
		this.isRedirect = isRedirect;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public boolean isRedirect() {
		return isRedirect;
	}

	public void setRedirect(boolean isRedirect) {
		this.isRedirect = isRedirect;
	}

	public boolean isTiles() {
		return isTiles;
	}

	public void setTiles(boolean isTiles) {
		this.isTiles = isTiles;
	}

	public void go(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		if (isTiles) {
			tilesGO(getUrl(), request, response);
		} else if (isRedirect()) {
			redirect(getUrl(), request, response);
		} else {
			dispatch(getUrl(), request, response);
		}
	}
	
	
	private void tilesGO(String tname,HttpServletRequest request,HttpServletResponse response){
		
		TilesContainer container = ServletUtil.getContainer(
		        request.getSession().getServletContext());
		container.render(tname, request,response);
	}
	
	
	private void dispatch(String urls,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatch=request.getRequestDispatcher(urls);
		dispatch.forward(request, response);
	}
	
	private void redirect(String urls,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect(urls);
	}
	
	public String toString() {
		return "ActionForward [isRedirect=" + isRedirect + ", isTiles="
				+ isTiles + ", url=" + url + "]";
	}

}
